<template>
  <div class="jeecg-basic-table order-list-view">
    <a-modal v-model:visible="showModal" :title="currentType" @ok="handleOk">
      <span style="margin-left: 20px">{{ currentType }}人：</span>
      <a-select v-model:value="selAssignTo" allowClear placeholder="请选择" style="width: 200px; margin: 20px 0">
        <template v-for="(item, index) in userList" :key="index">
          <a-select-option :value="item.username">
            {{ item.realname }}
          </a-select-option>
        </template>
      </a-select>
    </a-modal>
    <div class="tip">
      <span>工单列表</span>
      <span class="tip-img"></span>
    </div>
    <div class="jeecg-search-layer">
      <a-form ref="form" :model="queryParam">
        <a-row :gutter="[16, 16]">
          <a-col :span="8">
            <a-form-item label="站点">
              <a-select v-model:value="queryParam.stationCode" allowClear placeholder="请选择站点">
                <template v-for="(item, index) in stationList" :key="index">
                  <a-select-option :value="item.stationCode">
                    {{ item.name }}
                  </a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工单编号">
              <a-input v-model:value="queryParam.orderNum" placeholder="请输入工单编号" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工单状态">
              <JDictSelectTag v-model:value="queryParam.status" placeholder="请选择工单状态" dictCode="order_status" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工单类型">
              <a-select v-model:value="queryParam.orderType" allowClear placeholder="请选择工单类型">
                <template v-for="(item, index) in odrerTypeList" :key="index">
                  <a-select-option :value="Number(item.value)">
                    {{ item.label }}
                  </a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-form-item>
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-divider type="vertical" />
              <a-button type="primary" @click="onAdd('')" v-auth="'order:add'">新增</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="jeecg-table-view">
      <a-table :loading="loading" rowKey="id" :dataSource="dataSource" :columns="columns" :pagination="false">
        <template v-slot:bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex == 'action'">
            <a @click="onAdd(record)">详情</a>
            <a-divider type="vertical" v-auth="'order:assign'" v-show="record.status === '0'" />

            <a @click="onAassgin(record, '分派')" v-auth="'order:assign'" v-show="record.status === '0'">分派</a>

            <template v-if="record.status === '1' && record.assignTo == username">
              <a-divider type="vertical" />
              <a @click="onSignback(record)">维修人员回退</a>
              <a-divider type="vertical" />
              <a @click="onRepair(record, 2)">维修处理</a>
            </template>

            <!-- <a-divider type="vertical" v-auth="'order:resign'" v-show="record.status === '0' && username === record.assignTo" /> -->

            <template v-if="record.status == '2' && record.assignTo == username && roleCodes == 'FACTORY_OWNER'">
              <a-divider type="vertical" />
              <a @click="onRedo(record)">回退</a>
              <a-divider type="vertical" />
              <a @click="onAudit(record)">结算</a>
            </template>

            <template v-if="record.status == '0'">
              <a-divider type="vertical" />
              <a @click="handleDelete(record)">删除</a>
            </template>
          </template>
        </template>
      </a-table>
      <Pagination
        v-model:current="ipagination.current"
        :pageSize="ipagination.pageSize"
        :total="ipagination.total"
        :showTotal="ipagination.showTotal"
        show-less-items
        show-quick-jumper
        @change="handlePageChange"
        @showSizeChange="onShowSizeChange"
      />
    </div>
    <!-- <div class="jeecg-table-view">
      <template v-if="mode == 'list'">
        <BasicTable @register="registerTable">
          <template #tableTitle> </template>
          <template #action="{ record }">
            <TableAction :actions="getTableAction(record)" />
          </template>
        </BasicTable>
      </template>
    </div> -->
    <FormDrawer ref="formDrawer" @oks="onInit" :username="username" :stationList="stationList" :odrerTypeList="odrerTypeList" :userList="userList" />

    <assginDialog ref="assginDialog" @oks="onInit" />

    <maintainDialog ref="maintainDialog" @oks="onInit" />
  </div>
</template>

<script lang="ts">
import { defineComponent, onActivated } from 'vue';
export default defineComponent({
  name: 'orderLists',
});
</script>

<script lang="ts" setup>
import { ref, watch, getCurrentInstance, onMounted, nextTick } from 'vue';
import {
  orderPageApi,
  orderListApi,
  orderDeleteApi,
  assginOrderApi,
  resignOrderApi,
  auditOrderApi,
  signbackOrderApi,
  redoOrderApi,
} from '/@/api/order/index';
import orderApi from '/@/api/order/index';
import { projectListApi } from '@/api/project';
import { Pagination } from 'ant-design-vue';
import { render } from '/@/utils/common/renderUtils';
import { JDictSelectTag } from '/@/components/Form';
import FormDrawer from './components/form.vue';
import DecisionDrawer from './components/decision.vue';
import { useGo } from '/@/hooks/web/usePage';
import { usePermission } from '/@/hooks/web/usePermission';
import { useUserStore } from '/@/store/modules/user';
import { ajaxGetDictItems } from '/@/utils/dict';
import { useListPage } from '/@/hooks/system/useListPage';
import { BasicTable, TableAction, ActionItem } from '/@/components/Table';
import { BasicColumn } from '/@/components/Table';
import { JVxeColumn, JVxeTypes } from '/@/components/jeecg/JVxeTable/types';
import { listAllByUserDepart } from '../system/user/user.api';
import { getUserData } from '../system/usersetting/UserSetting.api';
import { listNoCareTenant } from '/@/views/system/user/user.api';
import { stationListApi } from '/@/api/station/index';
import AssginDialog from './components/assgin-dialog.vue';
import MaintainDialog from './components/maintain-dialog.vue';
import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';

let stationList = ref([]);

let userList = ref([]);

let selAssignTo = ref('');

let { proxy } = getCurrentInstance();

const userStore = useUserStore();

const odrerTypeList = ref(userStore.dictItems.order_type);

const { isDisabledAuth } = usePermission();

const go = useGo();

let roleCodes = ref('');

let loading = ref(false);

let queryParam = ref({
  orderNum: '',
});

let orderDateTime = ref([]);
let regionList = ref([]);
let ipagination = ref({
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30'],
  showTotal: (total, range) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条';
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0,
});
let orderId = ref('');
// 数据源
let dataSource = ref([]);
// 字段
let columns: BasicColumn[] = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'id',
    width: 60,
    align: 'center',
    customRender: (t, r, index) => {
      return (ipagination.value.current - 1) * ipagination.value.pageSize + t.renderIndex + 1;
    },
  },
  {
    title: '工单编号',
    align: 'center',
    dataIndex: 'orderNum',
  },
  {
    title: '归属站点',
    align: 'center',
    dataIndex: 'stationCode',
    customRender: ({ text }) => {
      return stationList.value.find((_) => _.stationCode === text)?.name;
    },
  },
  {
    title: '工单状态',
    align: 'center',
    dataIndex: 'status',
    customRender: (t, r, index) => {
      let CONFIG = {
        0: '待分派',
        1: '待办',
        2: '待审核',
        3: '已完成',
      };
      return CONFIG[t.value]; // === '0' ? '待办' : t.value === '1' ? '待审核' : '办结';
    },
  },
  {
    title: '工单类型',
    align: 'center',
    dataIndex: 'orderType',
    customRender: (t, r, index) => {
      return odrerTypeList.value.find((_) => _.value === t.value + '')?.label || '';
    },
  },
  {
    title: '工单内容',
    align: 'center',
    dataIndex: 'orderDetail',
  },
  {
    title: '处理人',
    align: 'center',
    dataIndex: 'assignTo',
    customRender: (t, r, index) => {
      return userList.value.find((_: any) => _.username == t.value + '')?.realname || '';
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
  },
];

const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  designScope: 'order-list',
  tableProps: {
    title: '工单列表',
    api: orderListApi,
    columns,
    size: 'small',
    formConfig: {
      // labelWidth: 200,
      // schemas: searchFormSchema,
    },
    actionColumn: {
      width: 190,
      fixed: 'right',
    },
  },
});

/**
 * 操作栏
 */
function getTableAction(record): ActionItem[] {
  return [
    {
      label: '详情',
      onClick: onAdd.bind(null, record),
      // ifShow: () => hasPermission('system:user:edit'),
    },
    {
      label: '分派',
      onClick: onAassgin.bind(null, record),
      // ifShow: () => hasPermission('system:user:edit'),
    },
    // {
    //   label: '决策配置',
    //   onClick: handleDecision.bind(null, record),
    // },
    // {
    //   label: '删除',
    //   onClick: handleDelete.bind(null, record),
    // },
  ];
}
let username = ref('');

let showModal = ref(false);
const [registerTable, { reload, updateTableDataRecord }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;

// 列表模式 => list /卡片模式 => card
let mode = ref('list');

// 项目列表
let projectList = ref([]);

// 工单列表
let orderList = ref([]); //ref(userStore.getorderList);

let currentType = ref('');
watch(
  () => queryParam.value.orderId,
  (dataValue) => {
    let data = orderList.value.find((k) => k.id == dataValue);
    if (data) {
      Object.assign(queryParam.value, {
        orderCode: data.orderCode,
        name: data.name,
      });
    }
  }
);

watch(
  () => orderDateTime.value,
  (dateLists) => {
    let startTime = '';
    let endTime = '';
    if (dateLists && dateLists.length > 0) {
      let [a, b] = dateLists;
      startTime = a;
      endTime = b;
    } else {
      startTime = '';
      endTime = '';
    }
    Object.assign(queryParam.value, {
      // 创建时间结束
      createTimeEnd: startTime,
      // 创建时间开始
      createTimeStart: endTime,
    });
  }
);

watch(
  () => mode.value,
  (e) => {
    if (e == 'list') {
      ipagination.value.pageSize = 10;
    } else {
      ipagination.value.pageSize = 9;
    }
    onInit();
  }
);

/**
 * 初始化数据列表
 */
function onInit() {
  let { current, pageSize } = ipagination.value;
  let data = {
    current,
    size: pageSize,
  };
  let keys = Object.keys(queryParam.value);
  Object.values(queryParam.value).map((_, i) => {
    if (_ !== '') {
      data[keys[i]] = _;
    }
  });
  loading.value = true;
  orderPageApi(data).then((res) => {
    loading.value = false;
    let { records, size, current, total } = res;
    Object.assign(ipagination.value, {
      current,
      pageSize: size,
      total,
    });
    dataSource.value = records;
  });
  ajaxGetDictItems('order_type');
}

function initorder() {
  orderListApi({}).then((res: any) => {
    orderList.value = res;
  });
}

/**
 * 切换当前页数
 */
function handlePageChange(page) {
  ipagination.value.current = page;
  onInit();
}

function onShowSizeChange(current, pageSize) {
  Object.assign(ipagination.value, { current, pageSize });
  onInit();
}

/**
 * 初始化项目列表
 */
function initProjectList() {
  projectListApi({}).then((res) => {
    projectList.value = res;
  });
}

/**
 * 打开新增弹窗
 */
function onAdd(row) {
  proxy.$refs.formDrawer.showDrawer(row);
}

function onAassgin(row, type) {
  proxy.$refs.assginDialog.visible = true;
  nextTick(() => {
    proxy.$refs.assginDialog.init({ orderId: row.id });
  });
  // selAssignTo.value = '';
  // currentType.value = type;
  // orderId.value = row.id;
  // showModal.value = true;
  // if (currentType.value === '分派') {
  //   const res = await listAllByUserDepart({ isAssign: 1 });
  //   userList.value = res.records;
  // } else {
  //   const res = await listAllByUserDepart({});
  //   userList.value = res.records;
  // }
}

function initListNoCareTenant() {
  listNoCareTenant({
    pageNo: 1,
    pageSize: 100000,
  }).then((res) => {
    userList.value = res.records;
  });
}

/**
 * 维修回退
 */
function onSignback(row) {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定退回当前工单?',
    centered: true,
    onOk() {
      signbackOrderApi({
        orderId: row.id,
      }).then((res) => {
        message.success('退回成功');
        onInit();
      });
    },
  });
}

function onRepair(row, idx) {
  proxy.$refs.maintainDialog.visible = true;
  nextTick(() => {
    proxy.$refs.maintainDialog.init({ orderId: row.id }, idx);
  });
}

/**
 * 厂长退回
 */
function onRedo({ id }) {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定退回当前工单?',
    centered: true,
    onOk() {
      redoOrderApi({ orderId: id }).then((res) => {
        message.success('退回成功');
        onInit();
      });
    },
  });
}

/**
 * 厂长退回
 */
function onAudit({ id }) {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定结算当前工单?',
    centered: true,
    onOk() {
      auditOrderApi({ orderId: id }).then((res) => {
        message.success('结算成功');
        onInit();
      });
    },
  });
}

function handleOk() {
  if (!selAssignTo.value) {
    message.error(`请选择${currentType.value}人`);
    return;
  }
  if (currentType.value === '分派') {
    assginOrderApi({ orderId: orderId.value, assignTo: selAssignTo.value }).then((res) => {
      message.success('分派成功');
      showModal.value = false;
      onInit();
    });
  } else {
    resignOrderApi({ orderId: orderId.value, assignTo: selAssignTo.value }).then((res) => {
      message.success('转派成功');
      showModal.value = false;
      onInit();
    });
  }
}

/**
 * 查看详情
 */
function handleDetail({ id }) {
  proxy.$refs.formDrawer.visible = true;
  nextTick(() => {
    proxy.$refs.formDrawer.init(id);
  });
}

/**
 * 配置工单决策
 */
function handleDecision({ orderCode }) {
  proxy.$refs.decisionDrawer.visible = true;
  nextTick(() => {
    proxy.$refs.decisionDrawer.init(orderCode);
  });
}

/**
 * 删除数据
 */
function handleDelete({ id }) {
  orderDeleteApi({ id }).then((res) => {
    message.success('删除成功!');
    onInit();
  });
}

/**
 * 跳转到plc编辑器
 */
function onOpenPlc({ id }) {
  go(`/meta/index?id=${id}`);
}

/**
 * 预览PLC图
 */
function onPreview({ id }) {
  // let args = [`id=${id}`, `r=${Date.now() + ''}`];
  // go(`/metaPreview?${args.join('&')}`);
  go(`/water/order/device?id=${id}`);
}

/**
 * 搜索数据
 */
function onSearch() {
  ipagination.value.current = 1;
  onInit();
}

/**
 * 切换卡片或者列表模式
 */
function onChangeMode() {
  mode.value = mode.value === 'list' ? 'card' : 'list';
}
onMounted(async () => {
  let res1 = await getUserData();

  initListNoCareTenant();

  roleCodes.value = userStore.getUserInfo['roleCodes'];

  username.value = res1.result.username;

  stationList.value = await stationListApi({});
  const res = await listAllByUserDepart({});
  // userList.value = res.records;
  onInit();
});

//   initProjectList();
//   initorder();
//   onInit();
// });
</script>

<style lang="less" scoped>
.order-list-view {
  margin: 12px;
  background: #fff;
  .tip {
    width: 100%;
    height: 44px;
    padding: 0 0 0 43.3px;
    background: url('@/assets/images/img-17.png') no-repeat;
    background-size: 100% 100%;
    line-height: 44px;
    span {
      font-size: 16px;
      color: #fff;
    }
  }
  .jeecg-search-layer {
    margin: 0 0 17px;
    padding: 12px 15px;
    background: #fff;
    border-radius: 8px;
    .ant-form {
      max-width: auto;
      .ant-form-item {
        margin-bottom: 24px;
      }
      :deep(.ant-col) {
        width: auto;
      }
    }
  }
  .jeecg-table-view {
    margin: 24px;
    .ant-pagination {
      padding: 12px 0;
    }
  }
}
</style>
